package me.kuye.jkuye.core;

import java.util.List;

import me.kuye.jkuye.config.Constants;
import me.kuye.jkuye.config.Handlers;
import me.kuye.jkuye.config.Interceptors;
import me.kuye.jkuye.config.JKuyeConfig;
import me.kuye.jkuye.config.Plugins;
import me.kuye.jkuye.config.Routes;
import me.kuye.jkuye.log.Logger;
import me.kuye.jkuye.plugin.IPlugin;

public class Config {
	private static final Constants constants = new Constants();

	private static final Plugins plugins = new Plugins();

	private static final Handlers handlers = new Handlers();

	private static final Interceptors interceptors = new Interceptors();

	private static final Routes routes = new Routes() {
		public void config() {
		}
	};
	private static Logger logger;

	public static void init(JKuyeConfig jKuyeConfig) {
		jKuyeConfig.configConstant(constants);
		jKuyeConfig.configRoute(routes);
		initLoggerFactory();
		jKuyeConfig.configPlugin(plugins);
		startPlugins();
		jKuyeConfig.configInterceptor(interceptors);
		jKuyeConfig.configHandler(handlers);

	}

	private static void startPlugins() {
		List<IPlugin> pluginList = Plugins.getPluginList();
		if (pluginList == null) {
			return;
		}
		for (IPlugin plugin : pluginList) {
			try {
				if (plugin instanceof me.kuye.jkuye.plugin.activerecord.ActiveRecordPlugin) {
					me.kuye.jkuye.plugin.activerecord.ActiveRecordPlugin arp = (me.kuye.jkuye.plugin.activerecord.ActiveRecordPlugin) plugin;

					if (arp.getDevMode() == null) {
						arp.setDevMode(constants.getDevMode());
					}
				}

				if (plugin.init() == false) {
					String message = "the error in the " + plugin.getClass().getName() + " plugin";
					logger.error(message);
					throw new RuntimeException(message);
				}
			} catch (Exception e) {
				String message = "Plugin start error: " + plugin.getClass().getName() + ". \n" + e.getMessage();
				logger.error(message, e);
				throw new RuntimeException(message, e);
			}
		}

	}

	private static void initLoggerFactory() {
		Logger.init();
		logger = Logger.getLogger(Config.class);
		JKuyeFilter.initLogger();
	}

	public static Constants getConstants() {
		return constants;
	}

	public static Plugins getPlugins() {
		return plugins;
	}

	public static Handlers getHandlers() {
		return handlers;
	}

	public static Interceptors getInterceptors() {
		return interceptors;
	}

	public static Routes getRoutes() {
		return routes;
	}

	public static Logger getLogger() {
		return logger;
	}
	
}
